<template>
  <div id="Main_vue">
    <div class="toolbar">
      <el-form :inline="true">
        <el-form-item>
          <el-button type="primary" size="small" @click="connect()" :disabled="recordForm.isconn" icon="el-icon-mobile-phone">远程监控</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" :disabled="!recordForm.isconn" icon="el-icon-picture-outline" @click="chartToggle()">监控图表</el-button>
        </el-form-item>
        <el-form-item>
          <el-button-group>
            <el-button type="primary" size="small" :disabled="!recordForm.isconn||ontotal===0" icon="el-icon-minus" @click="weaken()"></el-button>
            <el-button type="primary" size="small" :disabled="!recordForm.isconn">调节亮度</el-button>
            <el-button type="primary" size="small" :disabled="!recordForm.isconn||ontotal===ltotal" icon="el-icon-plus" @click="strengthen()"></el-button>
          </el-button-group>
        </el-form-item>
        <el-form-item>
          <el-button-group>
            <el-button type="primary" size="small" :disabled="!recordForm.isconn||!working" icon="el-icon-close" @click="turnpumpoff()"></el-button>
            <el-button type="primary" size="small" :disabled="!recordForm.isconn">水泵开关</el-button>
            <el-button type="primary" size="small" :disabled="!recordForm.isconn||working" icon="el-icon-check" @click="turnpumpon()"></el-button>
          </el-button-group>
        </el-form-item>
        <el-form-item>
          <el-button type="success" size="small" @click="configToggle()" icon="el-icon-setting">监控配置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-row>
      <el-col :span="24">
        <div id="logs_charts"></div>
        <el-card shadow="always" class="msglist" id="logs_list" :body-style="{padding:'0'}">
          <ul>
            <li class="log" v-for="log in logs" :key="index">{{log.msg}}</li>
          </ul>
        </el-card>
      </el-col>
      
    </el-row>
    <el-dialog title="远程配置" :visible.sync="recordForm.visible">
      <el-form ref="recordForm" class="recordForm" label-width="80px" :model="recordForm" :rules="configRules">
        <el-form-item label="模式" prop="protocol">
            <el-select v-model="recordForm.protocol" placeholder="请选择">
              <el-option label="普通ws模式" value="ws"/>
              <el-option label="加密wss模式" value="wss"/>
            </el-select>
        </el-form-item>
        <el-form-item label="IP" prop="ip">
          <el-input v-model="recordForm.ip" placeholder="请输入远程ip地址"></el-input>
        </el-form-item>
        <el-form-item label="端口" prop="port">
          <el-input v-model="recordForm.port" placeholder="请输入远程端口"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="configToggle()">取 消</el-button>
        <el-button type="primary" @click="saveConfig()">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import HighCharts from "highcharts";
export default {
  data() {
    return {
      wsclient: null,
      recordForm: {
        protocol: "ws",
        ip: "localhost",
        port: "5000",
        visible: false,
        isconn: false
      },
      configRules: {
        protocol: [
          { required: true, message: "请选择传输模式", trigger: "blur" }
        ],
        ip: [{ required: true, message: "请输入远程ip地址", trigger: "blur" }],
        port: [{ required: true, message: "请输入远程端口", trigger: "blur" }]
      },
      logs: [
        { msg: "基于物联网植物智能养殖系统" },
        { msg: "请点击远程按钮开始监测" }
      ],
      ontotal: 0,
      ltotal: 0,
      working: false,
      chart: null,
      chartvisible: false
    };
  },
  mounted() {
    setTimeout(() => {
      let defaultData = (() => {
        let data = [];
        let time = new Date().getTime();
        for (let i = -19; i <= 0; i += 1) {
          data.push({ x: time + i * 1000, y: NaN });
        }
        return data;
      })();
      HighCharts.setOptions({ global: { useUTC: false } });
      this.chart = HighCharts.chart("logs_charts", {
        chart: {
          backgroundColor: "transparent",
          type: "spline"
        },
        title: {
          text: "自动灌溉实时数据(温度、湿度、光照)",
          style: {
            color: "#fff"
          }
        },
        xAxis: {
          type: "datetime"
        },
        yAxis: {
          title: {
            text: null
          }
        },
        series: [
          {
            name: "摄氏温度",
            data: defaultData
          },
          {
            name: "相对湿度",
            data: defaultData
          },
          {
            name: "光照强度",
            color: "yellow",
            data: defaultData
          }
        ]
      });
    }, 500);
  },
  methods: {
    connect() {
      if (this.recordForm.isconn) {
        this.$message("已连接成功，无需再次连接");
        return false;
      }
      let that = this;
      that.wsclient = new WebSocket(
        this.recordForm.protocol +
          "://" +
          this.recordForm.ip +
          ":" +
          this.recordForm.port
      );
      that.wsclient.onopen = function() {
        that.recordForm.isconn = true;
        that.$notify({
          title: "成功",
          message: "远程监控连接成功",
          type: "success"
        });
      };
      that.wsclient.onmessage = function(evt) {
        let data = JSON.parse(evt.data);
        if ("time" in data) {
          if (data.ontotal !== that.ontotal) {
            that.ontotal = data.ontotal;
            that.ltotal = data.ltotal;
          }
          that.working = data.working;
          if (that.chart) {
            data.time = new Date(data.time).getTime();
            that.chart.series[0].addPoint(
              [data.time, Number.parseFloat(data.temp, 10)],
              true,
              true
            );
            that.chart.series[1].addPoint(
              [data.time, Number.parseFloat(data.humi, 10)],
              true,
              true
            );
            that.chart.series[2].addPoint(
              [data.time, Number.parseInt(data.illu, 10)],
              true,
              true
            );
            var points =
              that.chart.series[Number.parseInt(Math.random() * 3)].points;
            that.chart.tooltip.refresh(points[points.length - 1]);
          }
        }
        that.logs.push(data);
      };
      that.wsclient.onclose = function() {
        that.recordForm.isconn = false;
      };
      that.wsclient.onerror = function(evt) {
        that.recordForm.isconn = false;
        that.logs.push({ msg: "远程监控连接异常" });
      };
    },
    configToggle() {
      this.recordForm.visible = !this.recordForm.visible;
    },
    saveConfig() {
      var that = this;
      that.$refs["recordForm"].validate(function(valid) {
        if (valid) {
          that.$notify({
            title: "成功",
            message: "设置成功，请重新连接",
            type: "success"
          });
          try {
            that.recordForm.isconn = false;
            that.recordForm.visible = false;
            that.wsclient.close();
          } catch (err) {}
        } else {
          that.$message.warning("请填写数据有效性");
        }
      });
    },
    weaken() {
      this.$message({
        message: "暂无可用LED光源",
        type: "warning"
      });
      return false;
      if (this.ontotal !== 0) {
        this.wsclient.send("light," + (this.ontotal - 1).toString());
      }
    },
    strengthen() {
      this.$message({
        message: "暂无可用LED光源",
        type: "warning"
      });
      return false;
      if (this.ontotal !== this.ltotal) {
        this.wsclient.send("light," + (this.ontotal + 1).toString());
      }
    },
    turnpumpoff() {
      this.wsclient.send("0");
    },
    turnpumpon() {
      this.wsclient.send("1");
    },
    chartToggle() {
      this.chartvisible = !this.chartvisible;
    }
  },
  watch: {
    logs(o, n) {
      document.getElementById("logs_list").scrollTop = document.getElementById(
        "logs_list"
      ).scrollHeight;
    }
  }
};
</script>

<style>
#logs_charts {
  position: absolute;
  width: 55%;
  height: 300px;
  right: 0;
  top: 0;
}
.msglist {
  height: 72vh;
  background: #000;
  color: #fff;
  overflow-y: scroll;
}
.msglist .log {
  padding: 3px 0;
}
.msglist .log:last-child {
  padding-bottom: 80px;
}
#Main_vue ::-webkit-scrollbar-track-piece {
  background-color: #000;
}
#Main_vue ::-webkit-scrollbar {
  width: 5px;
  height: 5px;
}
#Main_vue ::-webkit-scrollbar-thumb {
  background-color: #bbb;
  background-clip: padding-box;
  min-height: 28px;
}
#Main_vue ::-webkit-scrollbar-thumb:hover {
  background-color: #bbb;
}
</style>
